//
//  GMGroupVC.m
//  Teecloud
//
//  Created by 小熊 on 2018/10/16.
//  Copyright © 2018年 小志. All rights reserved.
//
#import <SafariServices/SafariServices.h>
#import "GMGroupVC.h"
#import "XZGroupIntroduceVC.h"
#import "GMBuyVideoVC.h"
#import "GMBuyFile.h"
#import "GMReadPDFVC.h"
#import "XZNewsCaseVC.h"
#import "GMExaminationVC.h"
#import "GMExercisesVC.h"
#import "GMCoursePackageVC.h"
#import "XZMyGroupDetailVC.h"
#import "GMPlayerViewController.h"
#import "GMGroupImgCell.h"
#import "GMGroupCell.h"
#import "GMGroupModel.h"
#import "GMBaseNavigationController.h"
@interface GMGroupVC ()<UITableViewDataSource,UITableViewDelegate,SFSafariViewControllerDelegate,PYSearchViewControllerDelegate>
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) UITableView *tabView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@end

@implementation GMGroupVC

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self GetGroupList];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kWhiteColor;
    self.title = @"搜索结果";
    [self addRightBarButtonWithFirstImage:[UIImage imageNamed:@"search-white-64"] action:@selector(searchBtnClick)];
}

/**
 更新广告阅读计数

 @param addId 广告id
 */
-(void)updateReadCount:(NSString *)addId{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    //广告Id
    [dict setValue:addId forKey:@"adId"];
    
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"/ajax-api.ashx?$c=TeeyunApp&$m=UpdateAdCount&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                XZLog(@"计数成功");
            }else{
                XZLog(@"计数失败");
            }
            
        }else{
            XZLog(@"%@",error);
        }
    }];
}
#pragma mark - MJRefresh
-(void)GetGroupList{
    self.page =0;
    NSDictionary *dict= @{@"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                          @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"pageIndex":@(self.page),
                          @"pageSize":@(10),
                          @"key":self.searchText?self.searchText:@""
                          };
    kWeakObject(self)
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetGroupList&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [self.tabView.mj_footer endRefreshing];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSArray *arr = [GMGroupModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:RESULT_NAME_Data]];
                [weakself.dataArr removeAllObjects];
                [weakself.dataArr addObjectsFromArray:arr];
                if (weakself.dataArr.count == 0) {
                    [weakself.tabView setupEmptyDataText:@"暂无数据" secoundText:@"" buttonTit:@"" verticalOffset:0 emptyImage:NODATAIMG tapBlock:^{
                        
                    } butClick:^{
                        
                    }];
                }
                [weakself.tabView reloadData];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}
-(void)addMoreGroupList{
    self.page ++;
    NSDictionary *dict= @{@"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                          @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"pageIndex":@(self.page),
                          @"pageSize":@(10),
                          @"key":self.searchText?self.searchText:@""
                          };
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetGroupList&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSArray *arr = [GMGroupModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:RESULT_NAME_Data]];
                [weakself.dataArr addObjectsFromArray:arr];
                if (arr.count>0) {
                    [weakself.tabView.mj_footer endRefreshing];
    
                    [weakself.tabView reloadData];
                }else{//没有数据的时候就显示暂无数据
                    weakself.tabView.mj_footer.state = MJRefreshStateNoMoreData;
                }
            }else{
                [weakself.tabView.mj_footer endRefreshing];

                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [weakself.tabView.mj_footer endRefreshing];
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}
#pragma mark - setter
-(NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}
-(UITableView *)tabView{
    if (!_tabView) {
        _tabView = [UITableView zj_tableViewWithSuperview:self.view delegate:self style:UITableViewStylePlain constraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        _tabView.separatorStyle =UITableViewCellSeparatorStyleNone;
        [_tabView registerNib:[UINib nibWithNibName:@"GMGroupImgCell" bundle:nil] forCellReuseIdentifier:@"GMGroupImgCell"];
        [_tabView registerNib:[UINib nibWithNibName:@"GMGroupCell" bundle:nil] forCellReuseIdentifier:@"GMGroupCell"];
        _tabView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(addMoreGroupList)];
    }
    return _tabView;
}
#pragma mark - TableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GMGroupModel *model = self.dataArr[indexPath.row];
    if (model.IsAd) {
        GMGroupImgCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GMGroupImgCell" forIndexPath:indexPath];
        cell.model = model;
        return cell;
    }else{
        GMGroupCell *cell =[tableView dequeueReusableCellWithIdentifier:@"GMGroupCell" forIndexPath:indexPath];
        cell.model = model;
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
     return 80;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    GMGroupModel *model = self.dataArr[indexPath.row];
    if (model.IsAd) {//广告 就更新阅读计数
        [self updateReadCount:model.Id];
    }
    [self skipControllerWithNewsListModel:model];
}
/************************点击cell进行跳转**********************/
/**
 根据模型中RelType来进行跳转
 cell
 @param model XZBannerTops
 */
- (void)skipControllerWithNewsListModel:(GMGroupModel *)model{
    if (1 == [model.RelType integerValue]) {//model.RelType=1
        [self relTypeIsEqualOneSkipControllerWithNewsListModel:model];
    }else if (2 == [model.RelType integerValue]){//model.RelType=2
        [self skipOrganizationOrGroupWithNewsListModel:model];
    }else if (3 == [model.RelType integerValue]){//新闻资讯案例
        XZNewsCaseVC *newsCaseVC = [[XZNewsCaseVC alloc]init];
        newsCaseVC.newsId = model.Id;
        [self.navigationController pushViewController:newsCaseVC animated:true];
    }else if (4 == [model.RelType integerValue]){//广告详情页面基地址
        NSString *adUrlString = [NSString stringWithFormat:@"%@/%@",URL_ADURL,model.Id];
        SFSafariViewController *sfVC = [[SFSafariViewController alloc]initWithURL:[NSURL URLWithString:adUrlString]];
        sfVC.title = model.Name;
        sfVC.delegate = self;
        [self presentViewController:sfVC animated:YES completion:nil];
    }
}

/*
 **如model.RelType=1
 *进行相应的跳转
 */
- (void)relTypeIsEqualOneSkipControllerWithNewsListModel:(GMGroupModel *)model{
    NSInteger normalCode = [model.NormalCode integerValue];
    if (normalCode >0) {
        if (normalCode ==1) {
            [MBProgressHUD showErrorOrSuc:@"关联资源已下架或不可用" toView:self.view];
        }else if (normalCode ==2){
            [MBProgressHUD showErrorOrSuc:@"当前手机型 号非购买资源所用手机型号，你可以到“我的 - 主页 - 个人资料(付费资源管理)”模块申请变更手机型号。" toView:self.view];
        }
    }else{
      [self skipNormalCodeIsZeroControllerWithNewsListModel:model];
    }
}
/*
 *当model.NormalCode=0时 根据ResType及IsAdded进行相应的跳转
 */
- (void)skipNormalCodeIsZeroControllerWithNewsListModel:(GMGroupModel *)model{
  
    if (1 == [model.ResType integerValue]) {//视频
        if (!model.IsFree) {
            GMBuyVideoVC *buyVideoVC = [[GMBuyVideoVC alloc]init];
            buyVideoVC.ResType = model.ResType;
            buyVideoVC.resId = model.Id;
          
            [self.navigationController pushViewController:buyVideoVC animated:true];
            //            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 资源 - 学习资源 - 试看(视频)“页面" toView:self.view];
        }else{
            GMPlayerViewController *playerVC = [[GMPlayerViewController alloc]init];
            playerVC.resId = model.Id;
            [self.navigationController pushViewController:playerVC animated:true];
            //            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 我的 - 我的资源 - 播放 - 问题“页面" toView:self.view];
        }
    }else if (2 == [model.ResType integerValue]){//文档
        if (!model.IsFree) {
            GMBuyFile * buyFile = [[GMBuyFile alloc]init];
            buyFile.ResType = model.ResType;
           
            buyFile.resId = model.Id;
            [self.navigationController pushViewController:buyFile animated:true];
            //            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 资源 - 学习资源 - 详情(文档)“页面" toView:self.view];
        }else{
            GMReadPDFVC *myFileVC = [[GMReadPDFVC alloc]init];
            myFileVC.resId = model.Id;
            [self.navigationController pushViewController:myFileVC animated:true];
            //            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 我的 - 我的资源 - 文档“页面" toView:self.view];
        }
    }else if (3 == [model.ResType integerValue]){//习题
        if (!model.IsFree) {
            GMBuyFile *buyFile = [[GMBuyFile alloc]init];
            buyFile.ResType = model.ResType;
            buyFile.resId = model.Id;
           
            [self.navigationController pushViewController:buyFile animated:true];
            //            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 资源 - 学习资源 - 详情(习题、试卷)“页面" toView:self.view];
        }else{
#warning fromType不知道传什么
            GMExercisesVC *exercisesVC = [[GMExercisesVC alloc]init];
            exercisesVC.resId = model.Id;
            //            fromType
            [self.navigationController pushViewController:exercisesVC animated:true];
            //            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 我的 - 我的资源 - 习题 - 答题“页面" toView:self.view];
        }
    }else if (4 == [model.ResType integerValue]){//试卷
        if (!model.IsFree) {
            GMBuyFile *buyFile = [[GMBuyFile alloc]init];
            buyFile.ResType = model.ResType;
          
            buyFile.resId = model.Id;
            [self.navigationController pushViewController:buyFile animated:true];
            //            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 资源 - 学习资源 - 详情(习题、试卷)“页面" toView:self.view];
        }else{
            GMExaminationVC * examinationVC = [[GMExaminationVC alloc]init];
            examinationVC.resId = model.Id;
            [self.navigationController pushViewController:examinationVC animated:true];
            //            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 我的 - 我的资源 - 试卷考试 - 考试须知“页面" toView:self.view];
        }
    }else if (9 == [model.ResType integerValue]){//课程包
        if (!model.IsFree) {
            GMBuyFile *buyFile = [[GMBuyFile alloc]init];
            buyFile.ResType = model.ResType;
          
            buyFile.resId = model.Id;
            [self.navigationController pushViewController:buyFile animated:true];
            //            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 资源 - 学习资源 - 详情(课程包)“页面" toView:self.view];
        }else{
            GMCoursePackageVC *coursePackageVC = [[GMCoursePackageVC alloc]init];
            coursePackageVC.resId = model.Id;
            coursePackageVC.titleStr = model.Name;
            [self.navigationController pushViewController:coursePackageVC animated:true];
            //            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 我的 - 我的资源 - 课程包“页面" toView:self.view];
        }
    }
}
/*
 **如model.RelType=2
 * true=IsAdded：跳转”主页 - 我的 - 我的社团/小组 - 详情“页面
 * false=IsAdded：跳转”主页 - 资源 - 社团/小组 - 介绍“页面
 */
- (void)skipOrganizationOrGroupWithNewsListModel:(GMGroupModel *)model{
    if (!model.IsAdded) {
        XZGroupIntroduceVC *introduceVC = [[XZGroupIntroduceVC alloc]init];
        introduceVC.titileStr = model.Name;
        introduceVC.groupId = model.Id;
        [self.navigationController pushViewController:introduceVC animated:true];
    }else{
        XZMyGroupDetailVC *groupDetailVC = [[XZMyGroupDetailVC alloc]init];
        groupDetailVC.groupId = model.Id;
        groupDetailVC.titleStr = model.Name;
        [self.navigationController pushViewController:groupDetailVC animated:true];
    }
    
}
#pragma mark - SFSafariViewControllerDelegate -
- (void)safariViewControllerDidFinish:(SFSafariViewController *)controller{
    XZLog(@"击done");
}
-(void)searchBtnClick{
    PYSearchViewController *searchViewController = [PYSearchViewController searchViewControllerWithHotSearches:nil searchBarPlaceholder:@"请输入商品名称进行搜索" didSearchBlock:^(PYSearchViewController *searchViewController, UISearchBar *searchBar, NSString *searchText) {
        self.searchText = searchText;
        [self dismissViewControllerAnimated:YES completion:^{
            [self GetGroupList];
        }];
    }];
    searchViewController.searchTextField.textColor = [UIColor colorWithHexString:@"101010" andAlpha:1.0];
    searchViewController.searchTextField.tintColor = [UIColor colorWithHexString:@"101010" andAlpha:1.0];
    searchViewController.searchTextField.font = [UIFont systemFontOfSize:10.0f];
    searchViewController.searchBar.layer.cornerRadius = 16;
    searchViewController.searchBar.clipsToBounds = YES;
    searchViewController.searchBar.layer.borderWidth = 0.5;
    searchViewController.searchBar.layer.borderColor = [UIColor colorWithHexString:@"D7D7D7" andAlpha:1.0].CGColor;
    [searchViewController.cancelButton setTitleColor:kWhiteColor forState:UIControlStateNormal];
    searchViewController.cancelButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    
    searchViewController.delegate = self;
    searchViewController.hotSearchStyle = PYHotSearchStyleDefault;
    searchViewController.searchHistoryStyle = PYSearchHistoryStyleARCBorderTag;
    GMBaseNavigationController *base = [[GMBaseNavigationController alloc]initWithRootViewController:searchViewController];
    [self presentViewController:base animated:YES completion:nil];
}
@end
